$(function(){
    InvoiceExpress.init();

    var titleTypeVal = $("#invoice_title_type option:selected").val();
    $("input[name='invoiceInfo.email']").val($("#receiverEmailBack").val());
    if("company" == titleTypeVal){
        $("#taxNumber").val($("#taxNumberBack").val());
        $("input[name='invoiceInfo.companyName']").val($("#titleBack").val());
        $("input[name='invoiceInfo.address']").val($("#buyerAddressBack").val());
        $("input[name='invoiceInfo.contactTel']").val($("#buyerTelephoneBack").val());
        $("input[name='invoiceInfo.bankAccount']").val($("#bankAccountBack").val());
        $("input[name='invoiceInfo.accountBankAccount']").val($("#accountBankAccountBack").val());
        //显示公司名称input
        $("#invoice_title_type").siblings('.input').eq(1).show().siblings('.input').hide();
        //显示税号
        $('.invoice_more').show().find('.orderDl').eq(0).show().siblings('.orderDl').hide();
        $('.btn_invoice_more').html('填写更多信息<i class="icon_arrow"></i>').removeClass('invoice_more_show');
    }else if("personal" == titleTypeVal){
        $("input[name='invoiceInfo.personalName']").val($("#titleBack").val());
        $('.invoice_more').hide();
        $("#invoice_title_type").siblings('.input').eq(0).show().siblings('.input').hide();
    }
});
$("#taxNumber").blur(function(){
    //$('#taxNumberError').hide();
    var value = $(this).val().trim();
    $(this).val(value);
//    	   if(value !=""){
//    		   var reg = /^[A-Z0-9]{1,21}$/;
//    		   if(!reg.test(value)){
//    			   $('#taxNumberError').show();
//				   $(this).focus();
//    		   }
//    	   }
});

/*$("#add_address_detail").blur(function(){
 $('#add_address_detail_error').hide();
 var value = $(this).val().trim();
 if(value.length <5){
 $('#add_address_detail_error').css('display','inline-block');
 $('#add_address_detail_error').html('<i class="tip-icon tip-icon-error"></i>详细地址不能为空，且不小于五位。');
 $(this).focus();
 }
 });*/
//是否需要开发票
$("#a_isCheckedInvoice").bind("click",function(){
    var $this = $(this);
    if ( $this.hasClass('checked') ) {
        $("#isNeedInvoice").val("N");
        InvoiceExpress.cleanExpressGoods();
        //$('.js_invoiceType').removeAttr("checked");
    }else{
        $("#isNeedInvoice").val("Y");
        //if($('input[name="invoiceInfo.invoiceType"]:checked').val()==1){
            //电子发票
            if(checkSelectedInsurance()){
                $("input[name='insIncluded']").val("N");
                $('#invoice_insurance').show();
                if($('#invoice_insurance_check').attr("checked")){
                    $("input[name='insIncluded']").val("Y");
                    //包含保险且勾选
                    $('#invoiceAddressBox').show();
                    var firstAddressLi = $('.invoice_address_list li.active');
                    //最后一个除外
                    if (firstAddressLi.size() == 1 && !firstAddressLi.hasClass('address_add')) {
                        var add_address_name =firstAddressLi.children('.receiverName').text();
                        $('#invoiceFullName').val(add_address_name);

                        var add_address_mobile =firstAddressLi.children('.mobileNumber').text();
                        $('#invoiceMobile').val(add_address_mobile);

                        var add_address_province= firstAddressLi.children('.province').text();
                        $('#invoiceProvince').val(add_address_province);

                        var add_address_city= firstAddressLi.children('.city').text();
                        $('#invoiceCity').val(add_address_city);

                        var add_address_detail= firstAddressLi.children('.address').text();
                        $('#invoiceStreet').val(add_address_detail);

                        var add_address_zipcode= firstAddressLi.children('.postCode').text();
                        $('#invoicePostalCode').val(add_address_zipcode);
                    };
                }else{
                    $('#invoiceAddressBox').hide();
                }
            }else{
                $('#invoice_insurance').hide();
                $('#invoiceAddressBox').hide();
            }
        //}
    }
});

//发票类型
$("#invoice_title_type").change(function(){
    var $this = $(this);
    if ($this.val()=='company') {
        $('.invoice_more').show().find('.orderDl').eq(0).show().siblings('.orderDl').hide();
        $('.btn_invoice_more').html('填写更多信息<i class="icon_arrow"></i>').removeClass('invoice_more_show');
        $this.siblings('.input').eq(1).show().siblings('.input').hide();
    }else{
        $('.invoice_more').hide();
        $this.siblings('.input').eq(0).show().siblings('.input').hide();
    };
    $("#titleReminder").removeAttr("style");
});

//发票类型--电子和纸质 切换
$(".js_invoiceType").change(function(){
    var num = $(this).parent().index();
    if (num==0) {
        //电子发票
        if(checkSelectedInsurance()){
            $('#invoice_insurance').show();
            $("input[name='insIncluded']").val("N");
            if($('#invoice_insurance_check').attr("checked")){
                //包含保险且勾选
                $("input[name='insIncluded']").val("Y");
                $('#invoiceAddressBox').show();
                var firstAddressLi = $('.invoice_address_list li.active');
                //最后一个除外
                if (firstAddressLi.size() == 1 && !firstAddressLi.hasClass('address_add')) {
                    var add_address_name =firstAddressLi.children('.receiverName').text();
                    $('#invoiceFullName').val(add_address_name);

                    var add_address_mobile =firstAddressLi.children('.mobileNumber').text();
                    $('#invoiceMobile').val(add_address_mobile);

                    var add_address_province= firstAddressLi.children('.province').text();
                    $('#invoiceProvince').val(add_address_province);

                    var add_address_city= firstAddressLi.children('.city').text();
                    $('#invoiceCity').val(add_address_city);

                    var add_address_detail= firstAddressLi.children('.address').text();
                    $('#invoiceStreet').val(add_address_detail);

                    var add_address_zipcode= firstAddressLi.children('.postCode').text();
                    $('#invoicePostalCode').val(add_address_zipcode);
                };
            }else{
                $('#invoiceAddressBox').hide();
            }
        }else{
            $('#invoice_insurance').hide();
            $('#invoiceAddressBox').hide();
        }
        $('#invoiceEnailBox').show().find('.input').removeAttr('disabled');
        InvoiceExpress.cleanExpressGoods();
    }else{
        $('#invoice_insurance').hide();
        $('#invoiceAddressBox').show();
        $('#invoiceEnailBox').hide().find('.input').attr('disabled','disabled');
        var firstAddressLi = $('.invoice_address_list li.active');
        //最后一个除外
        if (firstAddressLi.size() == 1 && !firstAddressLi.hasClass('address_add')) {
            var add_address_name =firstAddressLi.children('.receiverName').text();
            $('#invoiceFullName').val(add_address_name);

            var add_address_mobile =firstAddressLi.children('.mobileNumber').text();
            $('#invoiceMobile').val(add_address_mobile);

            var add_address_province= firstAddressLi.children('.province').text();
            $('#invoiceProvince').val(add_address_province);

            var add_address_city= firstAddressLi.children('.city').text();
            $('#invoiceCity').val(add_address_city);

            var add_address_detail= firstAddressLi.children('.address').text();
            $('#invoiceStreet').val(add_address_detail);

            var add_address_zipcode= firstAddressLi.children('.postCode').text();
            $('#invoicePostalCode').val(add_address_zipcode);
        };

        InvoiceExpress.LoadGoodsAndcountPrice();
    };
});

$('#invoice_insurance_check').live('click',function(e){
    $("input[name='insIncluded']").val("N");
    if($(this).attr("checked")){
        // console.log('aa');
        $("input[name='insIncluded']").val("Y");
        $('#invoiceAddressBox').show();
        var firstAddressLi = $('.invoice_address_list li.active');
        //最后一个除外
        if (firstAddressLi.size() == 1 && !firstAddressLi.hasClass('address_add')) {
            var add_address_name =firstAddressLi.children('.receiverName').text();
            $('#invoiceFullName').val(add_address_name);

            var add_address_mobile =firstAddressLi.children('.mobileNumber').text();
            $('#invoiceMobile').val(add_address_mobile);

            var add_address_province= firstAddressLi.children('.province').text();
            $('#invoiceProvince').val(add_address_province);

            var add_address_city= firstAddressLi.children('.city').text();
            $('#invoiceCity').val(add_address_city);

            var add_address_detail= firstAddressLi.children('.address').text();
            $('#invoiceStreet').val(add_address_detail);

            var add_address_zipcode= firstAddressLi.children('.postCode').text();
            $('#invoicePostalCode').val(add_address_zipcode);
        };
    }else{

        $('#invoiceAddressBox').hide();
    }
});

function checkSelectedInsurance(){
    var bxGoodsIdList=[];
    $("ul.js_bxtab li.active").each(function(){
        var bxGoodsId=$(this).attr("data-id");
        if(bxGoodsId != undefined){
            bxGoodsIdList.push(bxGoodsId);
        }
    });
    if(bxGoodsIdList.length>0){
        return true;
    }else if($(".js_bx_checkbox").hasClass('checked')){
        return true;
    }else{
        return false;
    }
}

function processInvoiceInfo(command){

    var add_address_name = $('#add_address_name').val();
    $('#invoiceFullName').val(add_address_name);

    var add_address_mobile = $('#add_address_mobile').val();
    $('#invoiceMobile').val(add_address_mobile);

    var add_address_province= $('#add_address_province').val();
    var provincearray=add_address_province.split('@');
    add_address_province=provincearray[1];
    $('#invoiceProvince').val(add_address_province);

    var add_address_city= $('#add_address_city').val();
    var cityarray = add_address_city.split('@');
    add_address_city=cityarray[1];
    $('#invoiceCity').val(add_address_city);

    var add_address_detail= $('#add_address_detail').val();
    $('#invoiceStreet').val(add_address_detail);

    var add_address_zipcode= $('#add_address_zipcode').val();
    $('#invoicePostalCode').val(add_address_zipcode);

    var li = $("<li class='active'/>");
    var p = $("<p class='invoice_address_info1'/>").appendTo(li);
    $("<span class='addressee' title='"+add_address_name+"'/>").text(add_address_name).appendTo(p);
    $("<span/>").text(add_address_mobile).appendTo(p);
    p = $("<p class='invoice_address_info2'/>").appendTo(li);
    p.text(add_address_province+add_address_city+add_address_detail);
    $("<span class='invoice_modify'>修改</span>").appendTo(li);
    $("<i class='orderIcon_gou'></i>").appendTo(li);
    $("<p class='hide receiverName'/>").appendTo(li).text(add_address_name);
    $("<p class='hide mobileNumber'/>").appendTo(li).text(add_address_mobile);
    $("<p class='hide province'/>").appendTo(li).text(add_address_province);
    $("<p class='hide city'/>").appendTo(li).text(add_address_city);
    $("<p class='hide address'/>").appendTo(li).text(add_address_detail);
    $("<p class='hide postCode'/>").appendTo(li).text(add_address_zipcode);
    $("<p class='hide addressNo'/>").appendTo(li).text($('#addressNo').val());
    if(command=='add')
    {
        $('ul.invoice_address_list li.active').removeClass('active');
        li.insertBefore($('.address_add'));
    }else{
        $(li).replaceAll('ul.invoice_address_list li.active');
    }

};

function sendAddress(){

    var add_address_province= $('#add_address_province').val();
    var provincearray=add_address_province.split('@');
    add_address_province=provincearray[1];
    $('#invoiceProvince').val(add_address_province);

    var add_address_city= $('#add_address_city').val();
    var cityarray = add_address_city.split('@');
    add_address_city=cityarray[1];
    $('#invoiceCity').val(add_address_city);
    $.ajax({
        url : rootPath+"/invoice/address.do",
        type : 'post',
        data:{
            userName: $('#add_address_name').val(),
            mobileNumber:$('#add_address_mobile').val(),
            postCode:$('#add_address_zipcode').val(),
            province:$('#invoiceProvince').val(),
            city:$('#invoiceCity').val(),
            address:$('#add_address_detail').val(),
            addressNo:$('#addressNo').val()
        },
        async: false,
        dataType : 'json',
        success : function(data) {
            if(data.code==200){
                $('#addressNo').val(data.addressNo);
                try{
                    if(typeof(eval('showRelatedAddress') == "function")){
                        showRelatedAddress();
                    }
                }catch(e){}
            }

        }
    });
};

function freshAddress(data,flag,addressNo){
    if(data.success) {
        if(data.attributes != null && data.attributes.addressList != null && data.attributes.addressList.length > 0) {
            var htmlStr='';
            htmlStr+='<ul class="invoice_address_list">';
            $(data.attributes.addressList).each(function(idx, address){
                if(address!=null){
                    htmlStr+='<li>';
                    htmlStr+='<p class="invoice_address_info1"><span class="addressee">'+address.userName+'</span><span>'+address.mobileNumber+'</span></p>';
                    htmlStr+='<p class="invoice_address_info2">'+address.province+address.city+address.address+'</p>';
                    htmlStr+=' <span class="invoice_modify">修改</span>';
                    htmlStr+='<p class="hide receiverName" >'+address.userName+'</p>';
                    htmlStr+='<p class="hide mobileNumber" >'+address.mobileNumber+'</p>';
                    htmlStr+='<p class="hide province" >'+address.province+'</p>';
                    htmlStr+='<p class="hide city" >'+address.city+'</p>';
                    htmlStr+='<p class="hide address" >'+address.address+'</p>';
                    htmlStr+='<p class="hide postCode" >'+address.postCode+'</p>';
                    htmlStr+='<p class="hide addressNo" >'+address.addressNo+'</p>';
                    htmlStr+=' <i class="orderIcon_gou"></i>';
                    htmlStr+= '</li>';
                }
            });
            htmlStr+='<li class="address_add"><span>+</span><p>新增地址</p></li>';
            htmlStr+='</ul>';
            $(".invoice_address_box").html(htmlStr);
        }
        if(data.attributes == null && flag == "delete") {
            $(".addressNo").each(function(){
                var addressNoText = $(this).text();
                if(addressNoText == addressNo){
                    $(this).parent().remove();
                }
            });
        }
    }
};

var address_validation = {
    errorHtml:function($this,text){
        $this.addClass('yz_error').siblings('.error_text').css('display','inline-block').html('<i class="tip-icon tip-icon-error"></i>'+ text +'。').siblings('.ts_text').hide();
        if ($this[0].tagName.toLowerCase() != 'select') {
            $this.focus();
        };
    },
    okHtml:function($this){
        $this.removeClass('yz_error').siblings('.error_text').css('display','none').siblings('.ts_text').show();
    },
    allok:function(){
        var $address_yz = $('.address_yz');
        var _mobile = /^1[3-9]\d{9}$/;
        var _username = /^[a-zA-Z\u4e00-\u9fa5\s]+$/;
        var _youbian = /^\d{6}$/;
        var _address = /^[^\s][\u4E00-\u9FA5A-Za-z0-9-\s]+$/;

        for (var i = 0; i < $address_yz.length; i++) {
            var $thisYz = $address_yz.eq(i),
                value = $.trim($thisYz.val());

            //验证中英文姓名
            if($thisYz.attr('type_name')=='username'){
                if( value==''){
                    this.errorHtml($thisYz,'请输入姓名');
                    return false;
                }else if(!_username.test(value) && value!=''){
                    this.errorHtml($thisYz,'姓名只能包含汉字、字母和空格，请重新输入');
                    return false;
                }else{
                    this.okHtml($thisYz);
                }
				   //region 增加收件人实名制提示文案

                      /**
                       * 收件人实名制提示文案检测
                       */
                      function addresseeRealNameApp(options) {
                        var realNameInputSelector = options.realNameInputSelector;

                        var realNameInputValue = options.realNameInputValue;

                        var errorCallback = options.errorCallback;

                        //禁止字符规则
                        var addresseeRealNameRuleList = [
                            "先生",
                            "小姐",
                            "女士"
                        ];

                        //错误提示文本
                        var addresseeRealNameErrorText = '收件人请填写真实姓名';

                        //获取用户字符串
                        var addresseeRealName;
                        if (realNameInputSelector) {
                            addresseeRealName = $(realNameInputSelector).val();
                        }
                        if (realNameInputValue) {
                            addresseeRealName = realNameInputValue;
                        }

                        //开始验证
                        var addresseeRealNameRet = realNameValidate(addresseeRealName);

                        if (addresseeRealNameRet !== true) {
                            if (errorCallback) {
                                errorCallback.call(this, {
                                    errorMsg: addresseeRealNameErrorText
                                });
                                return false;
                            }
                        }

                        /**
                         * 实名验证
                         * @param realName 用户输入名称
                         * @returns {*} 是否验证通过
                         * 返回true表示验证成功
                         * 否则返回错误字符串
                         */
                        function realNameValidate(realName) {

                            //去除空白字符
                            realName = realName.replace(/\s/g, "");

                            //以下四种限制不能提交：1.小姐 2.先生 3.填一个字的 4.女士

                            //3.填一个字的
                            if (realName.length <= 1) {
                                return addresseeRealNameErrorText
                            }

                            //1.小姐
                            //2.先生
                            //4.女士
                            for (var i = 0; i < addresseeRealNameRuleList.length; i++) {
                                var addresseeRealNameRule = addresseeRealNameRuleList[i];
                                if (realName.indexOf(addresseeRealNameRule) !== -1) {
                                    return addresseeRealNameErrorText
                                }
                            }

                            return true;
                        }
                    }

                    var savedSelf = this;
                    var ret = addresseeRealNameApp({
                        realNameInputValue: value,
                        errorCallback: function (cbOptions) {
                            var errorMsg = cbOptions.errorMsg;
                            savedSelf.errorHtml($thisYz, errorMsg);
                        }
                    });
                    if (ret === false) {
                        return false;
                    }
                    //endregion
            }else if($thisYz.attr('type_name')=='mobile'){
                if(value==''){
                    this.errorHtml($thisYz,'请输入手机号');
                    return false;
                }else if(value.length==11 && !_mobile.test(value)){
                    this.errorHtml($thisYz,'暂不支持您输入的号码段，请联系驴妈妈客服<span class="c_f60">1010-6060</span>进行反馈');
                    return false;
                }else if(!_mobile.test(value) && value!=''){
                    this.errorHtml($thisYz,'手机号码必须为11位的数字，请重新输入');
                    return false;
                }else{
                    this.okHtml($thisYz);
                }
            }else if($thisYz.attr('type_name')=='city'){
                var cityOK = function(){
                    var city_select = $thisYz.parent().find('.address_yz');
                    for (var i = 0; i < city_select.length; i++) {
                        var thisVal = city_select.eq(i).val();
                        if(/选择/.test(thisVal)){return false;}
                    };
                    return true;
                }

                if(/选择/.test(value) || !cityOK()){
                    this.errorHtml($thisYz,'请选择省份、城市');
                    return false;
                }else{
                    this.okHtml($thisYz);
                }
            }else if($thisYz.attr('type_name')=='address'){
                if(value=='' || value.length<5){
                    this.errorHtml($thisYz,'详细地址不能为空，且不小于五位');
                    return false;
                } else {
                    this.okHtml($thisYz);
                }

            }else if($thisYz.attr('type_name')=='youbian'){
                if(!_youbian.test(value) && value!=''){
                    this.errorHtml($thisYz,'邮政编码只能为6位数字，请重新输入');
                    return false;
                }else{
                    this.okHtml($thisYz);
                }

            };


        };

        return true;
    }

};//validation结束


//新增地址
$(document).on('click','.address_add',function(e){

    if($("#invoiceAddressBox").find(".invoice_address_list li").size() >20 ){
        //收货地址限制提示
        nova.dialog({
            title: "温馨提示",  //标题
            content: '<div class="dialog_tip_content"><span class="tip-icon-big tip-icon-big-warning"></span>寄送地址上限20条</div>',
            width: 400,
            zIndex : 200,
            contentClone: false,  //是否克隆content内容
            okCallback: true
        });
        return;
    }
    //清空表单
    $('.address_yz').val('');
    //隐藏所有的报错信息
    $('.address_add_box .error_text').hide();

    //调用弹窗
    nova.dialog({
        title: "使用新地址",  //标题
        content: $('.address_add_box'),
        width: 600,
        zIndex : 200,
        okText : '保存并使用',
        wrapClass : 'invoice_address_dialog',
        cancelCallback: true,  //取消按钮
        contentClone: false,  //是否克隆content内容
        initCallback:function(){
            //$(this.wrap).find('.address_add_box').show();
        },
        okCallback: function(){

            if (address_validation.allok()) { //新增地址,校验是否通过
                sendAddress();
                processInvoiceInfo('add');
                //通过之后 清空表单
                $('.address_yz').val('');
            }else{
                return false; //校验失败，阻止弹窗关闭
            };

        }
    });
});

//修改地址
$(document).on('click','.invoice_modify',function(e){
    var $address_info1 = $(this).siblings('.invoice_address_info1');
    $('#addressNo').val($(this).siblings('.addressNo').text())
    // 拆分地区，参数带到弹窗里的大概代码，开发根据需求自己修改或去掉
    var getProvince ='';
    var getCity = '';

    var getDetail = $(this).siblings('.address').text();
    var name= $(this).siblings('.receiverName').text();
    var mobile =  $(this).siblings('.mobileNumber').text();
    var address = $(this).siblings('.invoice_address_info2').text();
    var zipCode=$(this).siblings('.postCode').text();
    var getProvince = $(this).siblings('.province').text();
    var getCity = $(this).siblings('.city').text();

    $('#add_address_province').find('option').each(function(){
        if($(this).text().indexOf(getProvince)>=0||getProvince.indexOf($(this).text())>=0){

            $(this).attr('selected',true);
            $('#add_address_province').change();
        }
    });

    $('#add_address_city').find('option').each(function(){
        if($(this).text().indexOf(getCity)>=0||getCity.indexOf($(this).text())>=0){

            $(this).attr('selected',true);
            $('#add_address_city').change();
        }
    });
    $('#add_address_name').val(name);
    $('#add_address_mobile').val(mobile);
    $('#add_address_detail').val(getDetail);
    $('#add_address_zipcode').val(zipCode);
    //隐藏所有的报错信息
    $('.address_add_box .error_text').hide();

    //调用弹窗
    nova.dialog({
        title: "修改地址",  //标题
        content: $('.address_add_box'),
        width: 600,
        zIndex : 200,
        okText : '保存并使用',
        wrapClass : 'invoice_address_dialog',
        cancelCallback: true,  //取消按钮
        contentClone: false,  //是否克隆content内容
        initCallback:function(){
            //$(this.wrap).find('.invoice_address_box').show();
        },
        okCallback: function(){

            if (address_validation.allok()) { //新增地址,校验是否通过
                processInvoiceInfo('modify');
                sendAddress();
                //通过之后 清空表单
                $('.address_yz').val('');
            }else{
                return false; //校验失败，阻止弹窗关闭
            };

        }
    });
});
//禁止字符规则
var addresseeRealNameRuleList1 = [
    "先生",
    "小姐",
    "女士"
];
function testRealNameValidate(realName) {

    //去除空白字符
    realName = realName.replace(/\s/g, "");

    //以下四种限制不能提交：1.小姐 2.先生 3.填一个字的 4.女士

    //3.填一个字的
    if (realName.length <= 1) {
        return false
    }

    //1.小姐
    //2.先生
    //4.女士
    for (var i = 0; i < addresseeRealNameRuleList1.length; i++) {
        var addresseeRealNameRule = addresseeRealNameRuleList1[i];
        if (realName.indexOf(addresseeRealNameRule) !== -1) {
            return false
        }
    }

    return true;
}
//选择寄送地址
$(document).on('click','.invoice_address_list li',function(e){
   //最后一个除外
    if (!$(this).hasClass('address_add')) {
        console.log('点击选择地址');
            var $address_info1 = $(this).find('.invoice_address_info1');
            var userName= $address_info1.find('span').eq(0).text();
        // newAddress.userName//为收件人
        if(testRealNameValidate(userName)){
          $(this).addClass('active').siblings().removeClass('active');
          
          var add_address_name =$(this).children('.receiverName').text();
          //alert(add_address_name);
          $('#invoiceFullName').val(add_address_name);
     
          var add_address_mobile =$(this).children('.mobileNumber').text();
         // alert(add_address_mobile);
          $('#invoiceMobile').val(add_address_mobile);
      
          var add_address_province= $(this).children('.province').text();
         // alert(add_address_province);
          $('#invoiceProvince').val(add_address_province);
     
          var add_address_city= $(this).children('.city').text();
         // alert(add_address_city);
          $('#invoiceCity').val(add_address_city);
                
          var add_address_detail= $(this).children('.address').text();
         // alert(add_address_detail);
          $('#invoiceStreet').val(add_address_detail);
            
          var add_address_zipcode= $(this).children('.postCode').text();
         // alert(add_address_zipcode);
          $('#invoicePostalCode').val(add_address_zipcode);
        }  
         
      };

});


var InvoiceExpress;
if (!InvoiceExpress) {
    InvoiceExpress = {};
};
InvoiceExpress.isQuery=false;
//信息验证
InvoiceExpress.check=function(){
    if(!InvoiceExpress.isShow()){
        return true;
    }
    if(InvoiceExpress.isQuery){
        return false;
    }
    var isOk=true;

    return isOk;

};
// 初始化省市联动select
InvoiceExpress.initCity = function(rootPath, parentId, destCitySelect) {

    $.ajax({
        url : rootPath + "/order/ticket/expressDic.do?parentId=" + parentId,
        type : 'get',
        async: false,
        dataType : 'json',
        success : function(data) {
            $.each(eval(data), function(i, item) {
                if(item!=null)
                {$(
                    "<option value='" + item.districtId + "@"
                    + item.districtName + "'>" + item.districtName
                    + "</option>").appendTo(destCitySelect);}
            });

        }
    });
};

//省市联动事件定义
InvoiceExpress.initCitySelectEvent = function(rootPath) {
    // 省份增加事件
    $("#add_address_province").change(function() {
        var city1Code = $("#add_address_province").find('option:selected').attr("value");
        $("#add_address_city").empty();
        $("<option>选择市</option>").appendTo("#add_address_city");
        InvoiceExpress.initCity(rootPath, city1Code, $("#add_address_city"));
    });
    // 城市增加事件
    $("#add_address_city").change(function() {
        // 这里需要得到所有的快递元素列表
        //if(!LVMAMA.order.wifi.checkVisiTime())
        //return;
        InvoiceExpress.isQuery=true;

        InvoiceExpress.isQuery=false;
    });
};
//快递相关内容初始化
InvoiceExpress.init = function() {
    $("#add_address_province").empty();
    $("<option>选择省</option>").appendTo("#add_address_province");
    $("#add_address_city").empty();
    $("<option>选择市</option>").appendTo("#add_address_city");
    InvoiceExpress.initCity(rootPath, 8, $("#add_address_province"));
    InvoiceExpress.initCitySelectEvent(rootPath);
};
//快递页面是否被显示
InvoiceExpress.isShow=function(){
    if(!$("#add_address_province")||!$("#add_address_province").val()){
        return false;
    }
    return true;
};

InvoiceExpress.cleanExpressGoods= function(){
    $("#invoiceExpressItemDiv").html("");
    checkStock();
}

InvoiceExpress.LoadGoodsAndcountPrice = function(){
    var address_city = $("#add_address_city").find('option:selected').attr("value");
    if (address_city == "选择市") {
        var	priceInfoHtml = "<span class='express_price'>请选择地址</span>";
        /*$("span.NewExpress_price").html(priceInfoHtml);*/
        $("#invoiceExpressItemDiv").html("");
        InvoiceExpress.loadDefaultGoods();
        checkStock();
        return;
    }
    var productExpId = $('#express_company_id').val();
    var addressParameterForm = {
        provinceId : $('#add_address_province').val().split("@")[0],
        cityId : $('#add_address_city').val().split("@")[0],
        productExpId : productExpId
    };
    $("#invoiceExpressItemDiv").html("");
    $.post("/scenic_front/order/express/findExpressGoodsAndPrice.do",addressParameterForm,function(data){
        if(data.success){
            var NewExpressItemHtml="";
            var expGoodsId = data.attributes.expressGoodsId;
            var quantity = data.attributes.quantity;
            if(expGoodsId==""){
                InvoiceExpress.loadDefaultGoods();
            }else{
                NewExpressItemHtml += "<input type='hidden' name='itemMap["
                    + data.attributes.expressGoodsId + "].goodsId' value='" +data.attributes.expressGoodsId
                    + "' autocomplete='off'/>";
                NewExpressItemHtml += "<input type='hidden' name='itemMap["
                    + data.attributes.expressGoodsId + "].visitTime' value='" +data.attributes.visitTime
                    + "' autocomplete='off'/>";
                NewExpressItemHtml += "<input type='hidden' name='itemMap["
                    + data.attributes.expressGoodsId
                    + "].quantity' value='"+quantity+"' goodsId="+data.attributes.expressGoodsId+" mainItem='false' />";

                $("#invoiceExpressItemDiv").html(NewExpressItemHtml);
            }
            checkStock();
        }
    },"JSON");
}
/*
 InvoiceExpress.loadDefaultGoods= function(){
 var NewExpressItemHtml="";
 var quantity=1;
 var today = localFormatDate(new Date().getTime());
 var goodsId = 2957293;

 NewExpressItemHtml += "<input type='hidden' name='itemMap["
 + goodsId + "].goodsId' value='" +goodsId
 + "' autocomplete='off'/>";
 NewExpressItemHtml += "<input type='hidden' name='itemMap["
 + goodsId + "].visitTime' value='" +today
 + "' autocomplete='off'/>";
 NewExpressItemHtml += "<input type='hidden' name='itemMap["
 + goodsId
 + "].quantity' value='"+quantity+"' goodsId="+goodsId+" mainItem='false' />";


 $("#invoiceExpressItemDiv").html(NewExpressItemHtml);
 }
 */

InvoiceExpress.loadDefaultGoods= function(){
    var today = localFormatDate(new Date().getTime());

    var productExpId = $('#express_company_id').val();
    var provinceIdString = $('#add_address_province').val().split("@")[0];
    var cityIdString = $('#add_address_city').val().split("@")[0];
    if(provinceIdString=='选择省'){
        provinceIdString  = '8';
    }
    if(cityIdString=='选择市'){
        cityIdString = '8';
    }
    var addressParameterForm = {
        provinceId : parseInt(provinceIdString),
        cityId : parseInt(cityIdString),
        productExpId : productExpId
    };
    $("#invoiceExpressItemDiv").html("");
    $.post("/scenic_front/order/express/findExpressGoodsAndPrice.do",addressParameterForm,function(data){
        if(data.success){
            var expGoodsId = data.attributes.expressGoodsId;
            var quantity = data.attributes.quantity;

            NewExpressItemHtml = "<input type='hidden' name='itemMap["
                + expGoodsId + "].goodsId' value='" +expGoodsId
                + "' autocomplete='off'/>";
            NewExpressItemHtml += "<input type='hidden' name='itemMap["
                + expGoodsId + "].visitTime' value='" +today
                + "' autocomplete='off'/>";
            NewExpressItemHtml += "<input type='hidden' name='itemMap["
                + expGoodsId
                + "].quantity' value='"+quantity+"' goodsId="+expGoodsId+" mainItem='false' />";


            $("#invoiceExpressItemDiv").html(NewExpressItemHtml);
        }
    },"JSON");


}

function localFormatDate(time){
    var date = new Date(time);

    var year = date.getFullYear(),
        month = date.getMonth()+1,//月份是从0开始的
        day = date.getDate();
    var newTime = year + '-' +
        (month < 10? '0' + month : month) + '-' +
        (day < 10? '0' + day : day);

    return newTime;
}

